<template>
  <div class="purchase-container">
    <el-page-header @back="goBack" title="返回">
      <template #content>
        <h1>{{ courseInfo.name }} - 课程详情</h1>
      </template>
    </el-page-header>
    
    <div v-loading="loading" class="purchase-content">
      <!-- 课程基本信息 -->
      <el-card shadow="hover" class="course-info">
        <el-row :gutter="20">
          <el-col :span="8">
            <img :src="courseInfo.couPic" class="course-cover">
          </el-col>
          <el-col :span="16">
            <h2>{{ courseInfo.name }}</h2>
            <p class="course-intro">{{ courseInfo.introduction }}</p>
            <div class="course-stats">
              <span><i class="el-icon-user"></i> {{ courseInfo.collectionCount }}人收藏</span>
              <span><i class="el-icon-view"></i> {{ courseInfo.clicks }}次浏览</span>
              <span><i class="el-icon-shopping-cart-2"></i> {{ courseInfo.purchaseCount }}人购买</span>
            </div>
            <div class="price-section">
              <span class="price">¥{{ courseInfo.price }}</span>
              <div class="action-buttons">
                <el-button 
                  type="primary" 
                  size="large" 
                  @click="handlePurchase"
                  :disabled="courseInfo.purchased || isTeacher"
                >
                  {{ courseInfo.purchased ? '已购买' : '立即购买' }}
                </el-button>
                <el-button 
                  type="success" 
                  size="large" 
                  @click="handleAddToCart"
                  :disabled="courseInfo.inCart || courseInfo.purchased || isTeacher"
                >
                  {{ courseInfo.inCart ? '已在购物车' : '加入购物车' }}
                </el-button>
              </div>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <!-- 课程评价 -->
      <el-card shadow="never" class="course-reviews" v-if="courseInfo.appraises.length > 0">
        <h3>课程评价</h3>
        <div class="review-list">
          <div v-for="review in courseInfo.appraises" :key="review.id" class="review-item">
            <div class="review-header">
              <span class="review-author">用户{{ review.studentId }}</span>
              <el-rate
                v-model="review.score"
                disabled
                show-score
                text-color="#ff9900"
                score-template="{value}分"
              />
            </div>
            <p class="review-content">{{ review.content }}</p>
          </div>
        </div>
      </el-card>
      <el-card shadow="never" class="course-reviews" v-else>
        <h3>课程评价</h3>
        <el-empty description="暂无评价" />
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from '@/utils/request'
import { useAuthStore } from '@/stores/auth'

const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()
const loading = ref(false)
const defaultCourseImage = ref(require('@/assets/fault.png'))

// 检查是否是教师角色
const isTeacher = computed(() => authStore.userInfo?.role === 1)

// 初始化课程信息对象
const courseInfo = ref({
  id: 0,
  name: '',
  introduction: '',
  couPic: '',
  price: 0,
  collectionCount: 0,
  clicks: 0,
  purchaseCount: 0,
  purchased: false,
  inCart: false,
  appraises: [],
  likeCount: 0,
  shareCount: 0,
  chapters: []
})

// 检查课程购买状态
const checkCourseOwnership = async (studentId, courseId) => {
  try {
    const response = await axios.get(`/api/student/${studentId}/has-course/${courseId}`, {
      headers: { Authorization: `Bearer ${authStore.token}` }
    })
    return response.data
  } catch (error) {
    console.error('检查课程所有权失败:', error)
    return false
  }
}

// 获取课程详情（包含购物车状态）
const fetchCourseDetail = async () => {
  try {
    loading.value = true
    const courseId = route.params.id
    
    // 获取课程基本信息
    const response = await axios.get(`http://localhost:8082/api/course-detail/${courseId}`)
    const courseData = response.data || response
    
    if (!courseData || typeof courseData !== 'object') {
      throw new Error('API返回数据格式不正确')
    }
    
    // 检查购物车状态和购买状态（如果已登录）
    let inCart = false
    let purchased = false
    
    if (authStore.isAuthenticated()) {
      try {
        const studentResponse = await axios.get(`/spoc/api/students/by-user-id/${authStore.userId}`)
        const studentData = studentResponse?.data || studentResponse
        const studentId = studentData?.studentId || studentData?.id
        
        if (studentId) {
          // 检查购物车状态
          const cartCheck = await axios.get(`/api/cart/check-course/${courseId}`, {
            params: { studentId },
            headers: { Authorization: `Bearer ${authStore.token}` }
          })
          inCart = cartCheck.data?.inCart || false
          
          // 检查购买状态
          purchased = await checkCourseOwnership(studentId, courseId)
        }
      } catch (error) {
        console.error('检查购物车或购买状态失败:', error)
      }
    }
    
    courseInfo.value = {
      id: courseData.id || 0,
      name: courseData.name || '未知课程',
      introduction: courseData.introduction || '暂无课程介绍',
      couPic: courseData.coverUrl || courseData.couPic || defaultCourseImage.value,
      price: courseData.price || 0,
      collectionCount: courseData.collectionCount || 0,
      clicks: courseData.clicks || 0,
      purchaseCount: courseData.purchaseCount || 0,
      purchased,
      inCart,
      appraises: courseData.appraises || [],
      likeCount: courseData.likeCount || 0,
      shareCount: courseData.shareCount || 0,
      chapters: courseData.chapters || []
    }
    
    // 如果是教师角色，跳转到课程管理页面
    if (isTeacher.value) {
      router.push({
        name: 'CoursePurchase',
        params: { id: courseInfo.value.id }
      })
    }
    
  } catch (error) {
    console.error('获取课程详情失败:', error)
    ElMessage.error('获取课程详情失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 处理添加到购物车
const handleAddToCart = async () => {
  try {
    // 1. 检查登录状态
    if (!authStore.isAuthenticated()) {
      await ElMessageBox.confirm('加入购物车需要登录，是否立即登录？', '登录提示', {
        confirmButtonText: '去登录',
        cancelButtonText: '取消',
        type: 'warning'
      })
      router.push('/login')
      return
    }

    // 2. 获取学生ID
    let studentId
    try {
      const response = await axios.get(`/spoc/api/students/by-user-id/${authStore.userId}`)
      const responseData = response?.data || response
      studentId = responseData?.studentId || responseData?.id
      
      if (!studentId) {
        throw new Error('无法获取学生信息')
      }
    } catch (error) {
      console.error('获取学生ID失败:', error)
      throw new Error('获取学生信息失败，请稍后再试')
    }

    // 3. 检查是否已购买该课程
    const hasCourse = await checkCourseOwnership(studentId, route.params.id)
    if (hasCourse) {
      ElMessage.warning('您已经购买过该课程，无需加入购物车')
      return
    }

    // 4. 确认加入购物车
    try {
      await ElMessageBox.confirm(
        `确定要将课程 "${courseInfo.value.name}" 加入购物车吗？`,
        '加入购物车确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'info'
        }
      )
    } catch (cancel) {
      ElMessage.info('已取消加入购物车')
      return
    }

    // 5. 调用添加到购物车API
    const { data } = await axios.post(
      `/api/cart/add-course/${route.params.id}`,
      { studentId },
      { 
        headers: { 
          Authorization: `Bearer ${authStore.token}`,
          'Content-Type': 'application/json'
        }
      }
    )

    ElMessage.success('课程已成功添加到购物车')
    courseInfo.value.inCart = true
    
  } catch (error) {
    console.error('加入购物车失败:', error)
    if (!error.message.includes('取消')) {
      let displayMsg = error.message
      if (error.response?.status === 400) {
        displayMsg = error.response.data?.message || displayMsg
      } else if (error.response?.status === 500) {
        displayMsg = '系统繁忙，请稍后再试'
      }
      ElMessage.error(displayMsg)
    }
  }
}

// 处理购买
const handlePurchase = async () => {
  try {
    // 1. 检查登录状态
    if (!authStore.isAuthenticated()) {
      await ElMessageBox.confirm('购买课程需要登录，是否立即登录？', '登录提示', {
        confirmButtonText: '去登录',
        cancelButtonText: '取消',
        type: 'warning'
      })
      router.push('/login')
      return
    }

    // 2. 获取学生ID
    let studentId
    try {
      const response = await axios.get(`/spoc/api/students/by-user-id/${authStore.userId}`)
      const responseData = response?.data || response
      studentId = responseData?.studentId || responseData?.id
      
      if (!studentId) {
        throw new Error('无法获取学生信息')
      }
    } catch (error) {
      console.error('获取学生ID失败:', error)
      throw new Error('获取学生信息失败，请稍后再试')
    }

    // 3. 检查是否已购买该课程
    const hasCourse = await checkCourseOwnership(studentId, route.params.id)
    if (hasCourse) {
      await ElMessageBox.alert('您已经购买过该课程，可以直接开始学习！', '购买提示', {
        confirmButtonText: '去学习',
        type: 'success',
        callback: () => {
          router.push(`/course/learn/${route.params.id}`)
        }
      })
      return
    }

    // 4. 确认购买
    try {
      await ElMessageBox.confirm(
        `<div class="purchase-confirm-content">
          <p>课程名称: <strong>${courseInfo.value.name}</strong></p>
          <p>课程价格: <strong class="price">¥${courseInfo.value.price || '0'}</strong></p>
          <p>确定要购买此课程吗？</p>
        </div>`, 
        '确认购买', 
        {
          confirmButtonText: '确认购买',
          cancelButtonText: '再考虑下',
          type: 'warning',
          dangerouslyUseHTMLString: true,
          customClass: 'purchase-confirm-box'
        }
      )
    } catch (cancel) {
      ElMessage.info('您已取消购买')
      return
    }

    // 5. 提交购买请求
    const { data: result, status } = await axios.post(
      `/api/course-detail/${route.params.id}/purchase`,
      { studentId },
      { 
        headers: { 
          Authorization: `Bearer ${authStore.token}`,
          'Content-Type': 'application/json'
        },
        timeout: 10000
      }
    ).catch(error => {
      const serverMessage = error.response?.data?.message
      const errorMsg = serverMessage || 
                      (error.code === 'ECONNABORTED' ? '请求超时' : '购买失败')
      throw new Error(errorMsg)
    })

    // 6. 购买成功后添加课程到学生课程表
    if (status === 200 || result?.success) {
      try {
        await axios.post(`/api/student/classes/${studentId}/courses/${route.params.id}`, {}, {
          headers: { Authorization: `Bearer ${authStore.token}` }
        })
        
        ElMessage.success('购买成功，课程已添加到您的学习列表')
        courseInfo.value.purchased = true
        
        // 如果购物车中有该课程，则从购物车移除
        if (courseInfo.value.inCart) {
          try {
            await axios.delete(`/api/cart/remove-course/${route.params.id}`, {
              params: { studentId },
              headers: { Authorization: `Bearer ${authStore.token}` }
            })
            courseInfo.value.inCart = false
          } catch (error) {
            console.error('从购物车移除课程失败:', error)
          }
        }
        
        // 刷新课程数据
        await fetchCourseDetail()
      } catch (error) {
        console.error('添加课程到学生课程表失败:', error)
        ElMessage.error('购买成功，但添加课程到学习列表失败，请联系客服')
      }
    } else {
      throw new Error(result?.message || '购买失败')
    }

  } catch (error) {
    console.error('购买流程错误:', error)
    if (!error.message.includes('取消')) {
      let displayMsg = error.message
      if (error.response?.status === 500) {
        displayMsg = '系统繁忙，请稍后再试'
      }
      ElMessage.warning(displayMsg)
    }
  }
}

// 返回上一页
const goBack = () => {
  router.go(-1)
}

onMounted(() => {
  fetchCourseDetail()
})
</script>

<style scoped>
.purchase-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.course-cover {
  width: 100%;
  height: 200px;
  object-fit: cover;
  border-radius: 4px;
}

.course-info {
  margin-bottom: 20px;
}

.course-intro {
  color: #666;
  margin: 10px 0;
  line-height: 1.6;
}

.price-section {
  margin-top: 20px;
  display: flex;
  align-items: center;
  gap: 20px;
}

.price {
  font-size: 24px;
  color: #f56c6c;
  font-weight: bold;
}

.course-stats {
  display: flex;
  gap: 15px;
  color: #888;
  margin: 15px 0;
}

.course-stats i {
  margin-right: 5px;
}

.course-reviews {
  margin-top: 20px;
}

.review-item {
  padding: 15px 0;
  border-bottom: 1px solid #f0f0f0;
}

.review-item:last-child {
  border-bottom: none;
}

.review-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.review-author {
  font-weight: bold;
}

.review-content {
  color: #333;
  line-height: 1.5;
}

.action-buttons {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}
</style>